use tauri::command;
use crate::ctp_commands::ctp::types::{ApiResponse, OrderRequest, CancelOrderRequest, WindowContext};
use crate::ctp_commands::ctp::state::*;
use crate::ctp_commands::ctp::utils::{validate_order_fields, copy_str_to_ctp_array, get_next_request_id, get_next_order_ref};
use crate::ctp_commands::ctp::validation;
use crate::logger;
use crate::audio_manager;

// 获取当前会话的FrontID和SessionID
fn get_session_front_and_session_id(session_id: &str) -> Option<(i32, i32)> {
    let front_session_map = get_order_front_session_map().lock().unwrap();
    let session_key = format!("session_{}", session_id);
    front_session_map.get(&session_key).copied()
}

#[command]
pub fn insert_order(
    session_id: String,
    order: OrderRequest,
    window_context: Option<WindowContext>,
) -> ApiResponse<String> {
    let context = window_context.unwrap_or_default();
    println!("🔍 [DEBUG] insert_order called with session_id: {}, order: {:?}, window_context: {:?}", session_id, order, context);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = get_trader_login_status().lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = get_trader_apis().lock().unwrap();
        let login_info = get_session_login_info().lock().unwrap();

        if let (Some(api), Some(account_config)) = (apis.get_mut(&session_id), login_info.get(&session_id)) {
            println!("✅ [DEBUG] Found Trader API and login info for session: {}", session_id);

            // 基础字段格式验证
            if let Err(validation_error) = validate_order_fields(&order) {
                println!("❌ [DEBUG] Order field validation failed: {}", validation_error);
                
                // 记录验证错误日志并播放错误提示音
                logger::log_validation_error("ORDER_FIELD_VALIDATION_FAILED", &order.instrument_id, &validation_error);
                audio_manager::play_error_notification();
                
                return Err(validation_error);
            }
            println!("✅ [DEBUG] Order field validation passed");
            
            // 使用 validation.rs 中的完整业务逻辑验证
            // 包括：合约信息、价格间距、手数限制、市场状态、资金、持仓等
            let instruments = get_ctp_instruments_data().lock().unwrap();
            let instrument_info = instruments.iter().find(|i| i.instrument_id == order.instrument_id).cloned();
            drop(instruments);
            
            if let Some(ref info) = instrument_info {
                // 验证手数是否符合合约限制
                if let Err(volume_error) = validation::validate_volume(order.volume, info) {
                    println!("❌ [DEBUG] Volume validation failed: {}", volume_error.message);
                    audio_manager::play_error_notification();
                    return Err(volume_error.message);
                }
                
                // 验证价格间距
                if let Err(price_error) = validation::validate_price_tick(order.price, info) {
                    println!("❌ [DEBUG] Price tick validation failed: {}", price_error.message);
                    audio_manager::play_error_notification();
                    return Err(price_error.message);
                }
                
                // 验证市场状态
                if let Err(market_error) = validation::validate_market_status(info) {
                    println!("❌ [DEBUG] Market status validation failed: {}", market_error.message);
                    audio_manager::play_error_notification();
                    return Err(market_error.message);
                }
                
                println!("✅ [DEBUG] Business logic validation passed");
            } else {
                println!("⚠️ [DEBUG] Contract info not found for {}, skipping business validation", order.instrument_id);
            }

            // 检查结算确认状态
            let settlement_confirmed = {
                let confirm_status = get_settlement_confirm_status().lock().unwrap();
                confirm_status.get(&session_id).copied().unwrap_or(false)
            };

            if !settlement_confirmed {
                println!("❌ [DEBUG] Settlement not confirmed for session: {}", session_id);
                return Err("结算结果未确认，请先进行结算确认后再进行交易操作".to_string());
            }
            println!("✅ [DEBUG] Settlement confirmed");

            // 引入CTP相关类型
            use ctp_trade_lib::*;

            // 创建输入报单结构
            let mut input_order = CThostFtdcInputOrderField::default();

            // 填充基本信息
            copy_str_to_ctp_array(&account_config.broker_id, &mut input_order.BrokerID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order.InvestorID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order.UserID);
            copy_str_to_ctp_array(&order.instrument_id, &mut input_order.InstrumentID);

            // 设置订单引用
            let order_ref = get_next_order_ref();
            copy_str_to_ctp_array(&order_ref, &mut input_order.OrderRef);

            // 存储窗口上下文，用于后续的精确通知
            {
                let mut context_map = get_order_window_context().lock().unwrap();
                context_map.insert(order_ref.clone(), context.clone());
                println!("🔍 [DEBUG] 存储订单窗口上下文: {} -> {:?}", order_ref, context);

                // 详细验证窗口上下文字段
                if let Some(window_id) = &context.window_id {
                    println!("✅ [DEBUG] 窗口ID已正确解析: {}", window_id);
                } else {
                    println!("❌ [DEBUG] 窗口ID为空或未解析");
                }

                if let Some(contract_code) = &context.contract_code {
                    println!("✅ [DEBUG] 合约代码已正确解析: {}", contract_code);
                } else {
                    println!("❌ [DEBUG] 合约代码为空或未解析");
                }
            }

            // 设置买卖方向
            input_order.Direction = if order.direction == "0" {
                THOST_FTDC_D_Buy as i8
            } else {
                THOST_FTDC_D_Sell as i8
            };

            // 设置价格和数量
            input_order.LimitPrice = order.price;
            input_order.VolumeTotalOriginal = order.volume;

            // 设置报单价格条件
            input_order.OrderPriceType = match order.order_type.as_str() {
                "1" => THOST_FTDC_OPT_AnyPrice as i8,     // 市价单
                "2" => THOST_FTDC_OPT_LimitPrice as i8,   // 限价单
                _ => THOST_FTDC_OPT_LimitPrice as i8      // 默认限价单
            };

            // 设置开平标志
            input_order.CombOffsetFlag[0] = match order.offset_flag.as_deref().unwrap_or("0") {
                "0" => THOST_FTDC_OF_Open as i8,          // 开仓
                "1" => THOST_FTDC_OF_Close as i8,         // 平仓
                "3" => THOST_FTDC_OF_CloseToday as i8,    // 平今
                "4" => THOST_FTDC_OF_CloseYesterday as i8, // 平昨
                _ => THOST_FTDC_OF_Open as i8             // 默认开仓
            };

            // 设置投机套保标志
            input_order.CombHedgeFlag[0] = match order.hedge_flag.as_deref().unwrap_or("1") {
                "1" => THOST_FTDC_HF_Speculation as i8,   // 投机
                "2" => THOST_FTDC_HF_Arbitrage as i8,     // 套利
                "3" => THOST_FTDC_HF_Hedge as i8,         // 套保
                _ => THOST_FTDC_HF_Speculation as i8      // 默认投机
            };

            // 设置有效期类型
            input_order.TimeCondition = match order.time_condition.as_deref().unwrap_or("3") {
                "1" => THOST_FTDC_TC_IOC as i8,           // 立即完成，否则撤销
                "2" => THOST_FTDC_TC_GFS as i8,           // 本节有效
                "3" => THOST_FTDC_TC_GFD as i8,           // 当日有效
                "4" => THOST_FTDC_TC_GTD as i8,           // 指定日期前有效
                "5" => THOST_FTDC_TC_GTC as i8,           // 撤销前有效
                _ => THOST_FTDC_TC_IOC as i8              // 默认当日有效
            };

            // 设置成交量类型
            input_order.VolumeCondition = match order.volume_condition.as_deref().unwrap_or("1") {
                "1" => THOST_FTDC_VC_AV as i8,            // 任何数量
                "2" => THOST_FTDC_VC_MV as i8,            // 最小数量
                "3" => THOST_FTDC_VC_CV as i8,            // 全部数量
                _ => THOST_FTDC_VC_AV as i8               // 默认任何数量
            };

            // 设置其他必要字段
            input_order.ContingentCondition = THOST_FTDC_CC_Immediately as i8;
            input_order.MinVolume = 1;
            input_order.ForceCloseReason = THOST_FTDC_FCC_NotForceClose as i8;
            input_order.IsAutoSuspend = 0;
            input_order.UserForceClose = 0;
            input_order.IsSwapOrder = 0;

            // 获取请求ID
            let request_id = get_next_request_id();
            input_order.RequestID = request_id;

            // 设置交易所代码（根据合约代码推断）
            let exchange_id = infer_exchange_id(&order.instrument_id);
            if !exchange_id.is_empty() {
                copy_str_to_ctp_array(&exchange_id, &mut input_order.ExchangeID);
                println!("📤 [DEBUG] Set ExchangeID: {}", exchange_id);
            } else {
                println!("📤 [DEBUG] ExchangeID not set, let CTP auto-detect");
            }

            println!("📤 [DEBUG] Calling ReqOrderInsert with order_ref: {}, request_id: {}", order_ref, request_id);

            // 清除之前的订单插入结果
            {
                let mut order_results = get_order_insert_results().lock().unwrap();
                order_results.remove(&order_ref);
            }

            // 调用CTP API插入订单
            let result = api.req_order_insert(&mut input_order, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqOrderInsert request sent successfully");
                
                // 记录挂单成功日志
                let direction_str = if order.direction == "0" { "买入" } else { "卖出" };
                logger::log_order_insert(
                    &order_ref,
                    &order.instrument_id,
                    direction_str,
                    order.volume,
                    order.price,
                    true,
                    None
                );
                
                Ok(format!("订单已成功提交，订单引用: {}", order_ref))
            } else {
                println!("❌ [DEBUG] ReqOrderInsert failed with code: {}", result);
                let error_msg = format!("提交订单失败，错误代码: {}", result);
                
                // 记录挂单失败日志
                let direction_str = if order.direction == "0" { "买入" } else { "卖出" };
                logger::log_order_insert(
                    &order_ref,
                    &order.instrument_id,
                    direction_str,
                    order.volume,
                    order.price,
                    false,
                    Some(&error_msg)
                );
                
                Err(error_msg)
            }
        } else {
            Err("未找到交易API会话或登录信息".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => {
            // 错误已在内部处理（记录日志和播放提示音）
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error_msg = "插入订单时发生系统错误".to_string();
            logger::log_api_error("insert_order", "system_panic", &error_msg);
            audio_manager::play_error_notification();
            
            ApiResponse {
                success: false,
                data: None,
                error: Some(error_msg),
            }
        },
    }
}

// 推断交易所代码
fn infer_exchange_id(instrument_id: &str) -> String {
    if instrument_id.len() >= 2 {
        let prefix = instrument_id.chars().take(2).collect::<String>().to_lowercase();
        match prefix.as_str() {
            // 上期所 (SHFE)
            "rb" | "hc" | "ss" | "wr" | "fu" | "bu" | "ru" | "sp" | "au" | "ag" |
            "cu" | "al" | "zn" | "pb" | "ni" | "sn" | "sc" | "lu" | "bc" | "nr" => "SHFE".to_string(),

            // 中金所 (CFFEX) - 通常是大写字母开头
            _ if instrument_id.starts_with("IF") ||
                 instrument_id.starts_with("IC") ||
                 instrument_id.starts_with("IH") ||
                 instrument_id.starts_with("IM") ||
                 instrument_id.starts_with("TS") ||
                 instrument_id.starts_with("TF") ||
                 instrument_id.starts_with("T") => "CFFEX".to_string(),

            // 大商所 (DCE) - 通常是小写字母
            "a" | "b" | "c" | "cs" | "i" | "j" | "jm" | "l" | "m" | "p" | "pp" | "v" | "y" |
            "bb" | "fb" | "jd" | "lh" | "pg" | "rr" | "eb" => "DCE".to_string(),

            // 郑商所 (CZCE) - 通常是大写字母开头
            _ if instrument_id.len() >= 2 => {
                let upper_prefix = instrument_id.chars().take(2).collect::<String>().to_uppercase();
                match upper_prefix.as_str() {
                    "CF" | "CY" | "FG" | "MA" | "OI" | "RM" | "SF" | "SM" | "SR" | "TA" | "ZC" |
                    "AP" | "CJ" | "LR" | "JR" | "PM" | "RI" | "RS" | "WH" | "PK" | "UR" | "SA" => "CZCE".to_string(),
                    _ => String::new(), // 让CTP自动处理
                }
            },
            _ => String::new(), // 让CTP自动处理
        }
    } else {
        String::new() // 合约代码太短，让CTP自动处理
    }
}

#[command]
pub fn cancel_order(
    session_id: String,
    cancel_request: CancelOrderRequest,
    window_context: Option<WindowContext>,
) -> ApiResponse<String> {
    let context = window_context.unwrap_or_default();
    println!("🔍 [DEBUG] cancel_order called with session_id: {}, cancel_request: {:?}, window_context: {:?}", session_id, cancel_request, context);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = get_trader_login_status().lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = get_trader_apis().lock().unwrap();
        let login_info = get_session_login_info().lock().unwrap();

        if let (Some(api), Some(account_config)) = (apis.get_mut(&session_id), login_info.get(&session_id)) {
            println!("✅ [DEBUG] Found Trader API and login info for session: {}", session_id);

            // 引入CTP相关类型
            use ctp_trade_lib::*;

            // 创建输入报单操作结构
            let mut input_order_action = CThostFtdcInputOrderActionField::default();

            // 填充基本信息
            copy_str_to_ctp_array(&account_config.broker_id, &mut input_order_action.BrokerID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order_action.InvestorID);
            copy_str_to_ctp_array(&account_config.account, &mut input_order_action.UserID);
            copy_str_to_ctp_array(&cancel_request.instrument_id, &mut input_order_action.InstrumentID);
            copy_str_to_ctp_array(&cancel_request.order_ref, &mut input_order_action.OrderRef);

            // 设置操作引用 (OrderActionRef是整数类型)
            let action_ref = get_next_order_ref();
            input_order_action.OrderActionRef = action_ref.parse::<i32>().unwrap_or(1);

            // 设置操作标志为删除
            input_order_action.ActionFlag = THOST_FTDC_AF_Delete as i8;

            // 动态获取FrontID和SessionID
            if let Some((front_id, session_id_num)) = get_session_front_and_session_id(&session_id) {
                input_order_action.FrontID = front_id;
                input_order_action.SessionID = session_id_num;
                println!("📤 [DEBUG] 动态获取到FrontID: {}, SessionID: {}", front_id, session_id_num);
            } else {
                // 如果没有会话级别的，尝试从订单级别获取
                let front_session_map = get_order_front_session_map().lock().unwrap();
                if let Some((front_id, session_id_num)) = front_session_map.get(&cancel_request.order_ref) {
                    input_order_action.FrontID = *front_id;
                    input_order_action.SessionID = *session_id_num;
                    println!("📤 [DEBUG] 从订单获取到FrontID: {}, SessionID: {}", front_id, session_id_num);
                } else {
                    println!("⚠️ [DEBUG] 未找到FrontID和SessionID，让CTP自动处理");
                }
            }

            // 设置交易所代码（必须设置）
            if let Some(exchange_id) = &cancel_request.exchange_id {
                copy_str_to_ctp_array(exchange_id, &mut input_order_action.ExchangeID);
            }

            // 获取请求ID
            let request_id = get_next_request_id();

            println!("📤 [DEBUG] Calling ReqOrderAction with order_ref: {}, action_ref: {}, request_id: {}",
                     cancel_request.order_ref, action_ref, request_id);

            // 调用CTP API撤销订单
            let result = api.req_order_action(&mut input_order_action, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqOrderAction successful");
                
                // 记录撤单成功日志
                logger::log_order_cancel(
                    &cancel_request.order_ref,
                    &cancel_request.instrument_id,
                    cancel_request.exchange_id.as_deref().unwrap_or(""),
                    true,
                    None
                );
                
                // 返回action_ref以便后续查询结果
                Ok(action_ref.to_string())
            } else {
                println!("❌ [DEBUG] ReqOrderAction failed with code: {}", result);
                let error_msg = format!("提交撤单失败，错误代码: {}", result);
                
                // 记录撤单失败日志
                logger::log_order_cancel(
                    &cancel_request.order_ref,
                    &cancel_request.instrument_id,
                    cancel_request.exchange_id.as_deref().unwrap_or(""),
                    false,
                    Some(&error_msg)
                );
                
                Err(error_msg)
            }
        } else {
            Err("未找到交易API会话或登录信息".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("撤销订单时发生系统错误".to_string()),
        },
    }
}

// 查询撤单结果
#[command]
pub async fn get_cancel_order_result(action_ref: String) -> ApiResponse<serde_json::Value> {
    println!("🔍 [DEBUG] get_cancel_order_result called with action_ref: {}", action_ref);

    // 等待撤单结果，最多等待5秒
    let mut attempts = 0;
    let max_attempts = 50; // 5秒，每次等待100ms

    while attempts < max_attempts {
        {
            let action_results = get_order_action_results().lock().unwrap();
            if let Some((success, message, order_ref)) = action_results.get(&action_ref) {
                let result = serde_json::json!({
                    "action_ref": action_ref,
                    "order_ref": order_ref,
                    "success": *success,
                    "message": message,
                    "status": if *success { "completed" } else { "failed" }
                });

                return ApiResponse {
                    success: true,
                    data: Some(result),
                    error: None,
                };
            }
        }

        // 等待100ms后重试
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        attempts += 1;
    }

    // 超时未收到结果
    let result = serde_json::json!({
        "action_ref": action_ref,
        "success": false,
        "message": "撤单结果查询超时，可能仍在处理中",
        "status": "timeout"
    });

    ApiResponse {
        success: false,
        data: Some(result),
        error: Some("撤单结果查询超时".to_string()),
    }
}

// 获取当前活跃的trader session
#[command]
pub fn get_active_trader_session() -> ApiResponse<String> {
    let login_status = get_trader_login_status().lock().unwrap();

    // 找到第一个已登录的session
    for (session_id, is_logged_in) in login_status.iter() {
        if *is_logged_in {
            return ApiResponse {
                success: true,
                data: Some(session_id.clone()),
                error: None,
            };
        }
    }

    ApiResponse {
        success: false,
        data: None,
        error: Some("未找到活跃的交易会话".to_string()),
    }
}

// 查询会话信息
#[command]
pub async fn get_session_info(session_id: String) -> ApiResponse<String> {
    if let Some((front_id, session_id_num)) = get_session_front_and_session_id(&session_id) {
        let info = format!("FrontID: {}, SessionID: {}", front_id, session_id_num);
        println!("🔍 [DEBUG] 查询会话信息: {}", info);
        ApiResponse {
            success: true,
            data: Some(info),
            error: None,
        }
    } else {
        let error = "未找到会话信息".to_string();
        println!("⚠️ [DEBUG] {}", error);
        ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        }
    }
}

